<?php

namespace App\Http\Controllers\Home;

use App\Helpers\Helpers;
use App\Model\Express;
use App\Model\Order;
use App\Model\OrderBonus;
use App\Model\ProductSku;
use App\Model\UserCoupon;
use App\Model\UserPoint;
use App\Model\WeChatFromId;
use App\Model\WineProduct;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Validation\Rule;

class OrderController extends BaseController
{

    public function index(Request $request)
    {
        $state = $request->input('state');
        $user = $this->loginUser();

        $query = Order::with([
            'product' => function($q){
                $q->select('id','name','chname','banner');
            }
        ]);
        $query = $query->where('create_user_id','=',$user->id);

        $arr = ['paying'=>0,'delivering'=>1,'cancel'=>2,'unclaimed'=>3,'expired'=>4,'receiving'=>5,'complete'=>6,'close'=>7,
            'pending'=>8,'refunding'=>9,'refunded'=>10];

        if (isset($arr[$state])) {
            $query = $query->where('state','=',$arr[$state]);
        }

        $items = $query->where('user_del','=',0)->orderBy('created_at','desc')
            ->select('id','out_trade_no','total_fee','product_id','product_name','product_chname','origin_price',
                'price','deliver_fee','quantity','is_pay','pay_time','create_user_id','state','is_delivery','pay_method')
            ->get();

        foreach ($items as $key => $order) {
            if ($order->state==3 && $order->expire_time && strtotime($order->expire_time) < time()){
                $order->state = 4;
                $order->save();
            }

        }

        return $this->success($items);
    }

    //创建订单
    public function store(Request $request)
    {
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }
        //购买用户
        $user = $this->loginUser();

        //验证规则
        $rules = [
//            'product_id' =>[
//                'required',
//                'numeric',
//                Rule::exists('wine_product','id')->whereNull('deleted_at')->where('online','yes')
//            ],
            'sku_id' => [
                'required',
                'numeric',
                Rule::exists('product_skus','id')->whereNull('deleted_at')
            ],
            'quantity' => 'required|numeric|min:1',
            'address_id' => [
                'required',
                'numeric',
                Rule::exists('t_user_addresses','id')->where(function($query) use($user){
                    $query->where('user_id',$user->id);
                })
            ],
            'pay_method' => 'required|in:1,2'
        ];

        //验证消息
        $message = [
            'product_id.exists' => '商品不存在或已下架',
            'address_id.exists' => '请重新选择地址',
            'pay_method.required' => '请选择支付方式'
        ];

        //验证请求
        if(!$this->requestValidate($request->all(),$rules,$message)){
            return $this->failed($this->error);
        }

        //$product = WineProduct::find($request->input('product_id'));

        $sku = ProductSku::find($request->input('sku_id'));
        $product = $sku->product;
        $d = $request->only('product_id','sku_id','quantity','address_id','pay_method');
        $d['product_id'] = $product->id;
        $d['category_id'] = $product->category_id;

        //判断商品库存
        if ($sku->sku < $d['quantity']) {
            return $this->failed('库存不足');
        }

        //减库存sku
        $sku->sku -= $d['quantity'];
        $sku->save();

        //订单金额信息
        //商品市场价格
        $d['origin_price']  = $sku->origin_price;

        if ($d['pay_method'] == 2) {
            $d['price']  = $sku->consume_price;

        }else{
            if ($d['quantity']<=2){
                $d['price']  = $sku->price;
            }elseif ($d['quantity']>=3 && $d['quantity']<=4){
                $d['price']  = $sku->price_3_4;
            }elseif ($d['quantity']>=5){
                $d['price']  = $sku->price_5;
            }
        }
        //商品价格


        if (!$d['price']){
            return $this->failed('商品信息错误，请稍后购买');
        }

        //商品未促销总金额
        $d['origin_product_total_fee'] =  $d['origin_price']*$d['quantity'];
        //商品促销总金额
        $d['product_total_fee'] =  $d['price']*$d['quantity'];
        //运费
        $d['deliver_fee'] = 0;

        $coupon = false;

        //订单其他信息
        $d['comment'] = $request->input('comment','');

        $d['product_name'] = $product->name;
        $d['product_chname'] = $product->chname;

        //创建订单
        $m = new Order();
        $m->out_trade_no = Helpers::createOrderOutTradeNo();
        $m->create_user_id = $user->id;
        $m->fill($d);
        //待支付
        $m->state = 0;
        //是否已支付
        $m->is_pay = "no";
        //是否已发货
        $m->is_delivery = "no";
        //订单总金额(包含运费)
        $m->total_fee = $m->product_total_fee + $m->deliver_fee;

        $arr = [];
        foreach ($sku->skuAttr as $attr){
            $arr[] = [
              'key' => $attr->attrLabelName,
              'value' => $attr->attrLabelValue,
            ];
        }

        $m->order_sku_attr = $arr;
        $m->sku_desc = $sku->desc;

        $m->save();

        //更新订单量统计
        $user->updateOrderCount();
        //添加地址信息
        $m->addAddressInfo($m->address_id,$user->id);

        WineProduct::updateOrderCount($m->product_id);


        return $this->success($m);
    }

    //详细
    public function show($id)
    {
        $item = Order::with([
            'product' => function($q){
                $q->select('id','name','chname','banner');
            },
            'product.covers'
        ])->where('create_user_id','=',$this->loginUserId())->find($id);

        if (!$item) return $this->notFond();

        return $this->success($item);
    }

    //确认收货
    public function complete($id)
    {
        if ($formid = request('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId,1);
        }

        $order = Order::where('create_user_id','=',$this->loginUserId())->find($id);

        if (!$order) return $this->notFond();

        if ($order->state == 5) {
            $order->state = 6;
            $order->finish_time = date('Y-m-d H:i:s');
            $order->save();

            //更新订单量统计
            User::updateOrderCountByUserId($order->create_user_id);

            WineProduct::updateOrderCount($order->product_id);

            //仅用于测试
            $test_bool = in_array($order->create_user_id,explode(',',env('DEV_USER_ID')));

            //支付方式是微信支付的订单分红
            if ($order->pay_method == 1 || $test_bool){
                OrderBonus::createBonus($order);
            }

            if ($order->pay_method == 2 && $order->consumePay){
                $order->consumePay->state = "order-complete";
                $order->consumePay->stateName = "已完成";
                $order->consumePay->save();
            }


            return $this->message('确认收获成功');
        }
        return $this->failed('fail');
    }

    //删除订单记录
    public function delete($id)
    {
        if ($formid = request('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId,1);
        }
        $order = Order::where('create_user_id','=',$this->loginUserId())->find($id);

        if (!$order) return $this->notFond();

        $can = [0];

        if (!in_array($order->state,$can)){
            return $this->failed('不能删除');
        }

        $order->user_del = 1;
        $order->user_del_time = Helpers::now();
        $order->save();

        //订单回库
        Order::skuReturnBySinge($order);

        return $this->message('删除成功');
    }

    //取消订单
    public function cancel($id)
    {
        if ($formid = request('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId,1);
        }

        $order = Order::find($id);

        if (!$order) return $this->notFond();

        $can = [0];

        if (!in_array($order->state,$can)){
            return $this->failed('只能取消待支付订单');
        }

        $order->state = 2;
        $order->save();

        //订单回库
        Order::skuReturnBySinge($order);

        return $this->message('取消成功');
    }

    public function consumePay($id)
    {
        if ($formid = request('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId,1);
        }

        $user = $this->loginUser();

        $order = Order::where('create_user_id','=',$user->id)->where('state','=',0)->find($id);

        if (!$order) $this->failed('订单不存在或已失效');

        if ($order->pay_method != 2) {
            return $this->failed('该订单不属于积分订单，如需使用积分支付请重新下单！');
        }

        if ($order->is_pay == "yes"){
            return $this->failed('订单已支付');
        }

        if ($order->total_fee>$user->point){
            return $this->failed('积分不足');
        }

        $order->pay_method = 2;
        $order->is_pay = "yes";
        $order->state = 1;
        $order->save();

        UserPoint::createOneRecord($order->create_user_id,-1*$order->total_fee,$order->product_chname.'-数量'.$order->quantity,'consume',$order->id,[
            'state' => 'order-delivery',
            'stateName' => '待发货',
            'ok' =>1,
        ]);

        return $this->success($order);
    }
}
